package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.WxHomeWindow;
import cn.com.dashihui.web.service.WxHomeWindowService;

@RequiresAuthentication
public class WxHomeWindowController extends BaseController{
	private WxHomeWindowService service = new WxHomeWindowService();

    public void index(){
        render("index.jsp");
    }

	public void page(){
		int pageNum = getParaToInt("pageNum", 0);
		if(pageNum==0){
			pageNum = getParaToInt(0, 1);
		}
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPage(pageNum, pageSize));
	}
	
	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：标题为空，2：标题过长，3：内容为空，4：链接为空，5：图片上传失败
	 */
	public void doAdd(){
		//缩略图
		UploadFile thumb = getFile("thumb");
		//标题
		String title = getPara("title");		
		//内容
		String content = getPara("content");
		//链接
		String link = getPara("link");
		//是否推送 0：否 1：是
		int isPopup=getParaToInt("isPopup",0);		
		//推送时间类型
		int pushDateType=getParaToInt("pushDateType",0);
		//推送时间
		String pushDate = getPara("pushDate");
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(content)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(link)){
			renderResult(4);
			return;
		}else{
			//保存
			WxHomeWindow article = new WxHomeWindow()
				.set("title", title)
				.set("content", content)
				.set("link", link)
				.set("isPopup", isPopup)
			    .set("pushDateType", pushDateType)
	/*		    .set("pushDate", pushDate)*/
			    .set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
			if(!StrKit.isBlank(pushDate)){
				article.set("pushDate", pushDate);
			}
			//如果上传了图片，则上传至FTP，并记录图片文件名
			if(thumb!=null){
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(5);
					return;
				}
				article.set("thumb", dir.concat(thumbFileName));
			}
			/*if(service.addArticle(article)){
				renderSuccess(service.findById(article.getInt("id")));
				renderSuccess();
				return;
			}*/
			article.save();
			renderSuccess();
			return;
		}
	}

	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：标题为空，2：标题过长，3：内容为空，4：链接为空，5：图片上传失败
	 */
	public void doEdit(){

		//缩略图
		UploadFile thumb = getFile("thumb");
		//标题
		String title = getPara("title");		
		//内容
		String content = getPara("content");
		//链接
		String link = getPara("link");

		//是否推送 0：否 1：是
		int isPopup=getParaToInt("isPopup",0);		
		//推送时间类型
		int pushDateType=getParaToInt("pushDateType",0);
		//推送时间
		String pushDate = getPara("pushDate");
		//弹窗ID
		int isPushId = getParaToInt("pushId",0);
		//旧图片
		String thumbOld = getPara("thumbOld");
		if(StrKit.isBlank(title)){
			renderResult(1);			
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(content)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(link)){
			renderResult(4);
			return;
		}else{
			//更新
			WxHomeWindow article = service.findById(isPushId)
					.set("title", title)
					.set("content", content)
					.set("link", link)
				    .set("isPopup", isPopup)
				    .set("pushDateType", pushDateType);

			if(!StrKit.isBlank(pushDate)){
				article.set("pushDate", pushDate);
			}else{
				article.set("pushDate", null);
			}
			if(thumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(5);
					return;
				}
				article.set("thumb", dir.concat(thumbFileName));
				if(service.editWxHomeWindow(article)){
					try {
						deleteFromFtp(thumbOld);
					} catch (IOException e) {
						logger.error("更新时，旧图片"+thumbOld+"删除失败！");
						e.printStackTrace();
					}
					renderSuccess(service.findById(Integer.valueOf(isPushId)));
					return;
				}
			}else if(service.editWxHomeWindow(article)){
				renderSuccess(service.findById(Integer.valueOf(isPushId)));
				return;
			}
		}
	}
	/**
	 * 关闭活动，把isClose状态改为1
	 */
	public void updateProperty(){
		int id = getParaToInt(0,0);
		if(id!=0){
			WxHomeWindow article = service.findById(id);
			article.set("isClose", 1);
			//然后再对记录进行删除
			service.editWxHomeWindow(article);
			logger.info("活动结束【"+id+"】");
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 删除消息
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if (id!=0) {
			service.Delete(id);
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
//	public void doDelete(){
//		int id = getParaToInt(0,0);
//		if(id!=0){
//			WxHomeWindow article = service.findById(id);
//			//先判断如果上传了图片，则删除图片
//			if(!StrKit.isBlank(article.getStr("thumb"))){
//				try {
//					deleteFromFtp(article.getStr("thumb"));
//				} catch (IOException e) {
//					logger.error("删除时，相关图片"+article.getStr("thumb")+"删除失败！");
//					e.printStackTrace();
//				}
//			}
//			//然后再对记录进行删除
//			article.delete();
//			logger.info("删除首页弹窗【"+id+"】，及其图片");
//			renderSuccess();
//			return;
//		}
//		renderFailed();
//	}
	
	/**
	 * 文本编辑中图片上传
	 */
	public void uploadimg(){
		UploadFile thumb = getFile();
		Map<String,Object> map = new HashMap<String,Object>();  
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
				map.put("error", 0);  
				map.put("url",PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));  
				renderJson(map);
		        return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);  
				map.put("message","图片上传失败");  
				renderJson(map);
			}
		}else{
			map.put("error", 1);  
			map.put("message","图片为空");  
			renderJson(map);
		}
	}
}
